package com.applink.sell_proof.widget;

import android.content.Context;
import android.text.Editable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class MyEditText extends EditText implements OnLongClickListener,
		OnFocusChangeListener {

	public MyEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setOnLongClickListener(this);
		setOnFocusChangeListener(this);
	}

	public MyEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		setOnLongClickListener(this);
		setOnFocusChangeListener(this);
	}

	public MyEditText(Context context) {
		super(context);
		setOnLongClickListener(this);
		setOnFocusChangeListener(this);
	}

	@Override
	public boolean onLongClick(View v) {

		Toast toast = Toast.makeText(v.getContext(), "My tool-tip text",
				Toast.LENGTH_LONG);
		int[] coordinator = new int[2];
		v.getLocationInWindow(coordinator);
		int screenWidth = getResources().getDisplayMetrics().widthPixels;
		int offsetX = coordinator[0] + v.getWidth() / 2 - screenWidth / 2;

		if (coordinator[1] - v.getHeight() < 0) {
			// show bottom
			toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, offsetX,
					coordinator[1] + v.getHeight());
		} else {
			// show top
			toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, offsetX,
					coordinator[1] - v.getHeight());
		}

		toast.show();
		return true;
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {

		Editable t = ((EditText) v).getText();

		if (hasFocus) {
			if ((t.length() == 1) && t.toString().equals("0")) {
				((EditText) v).setText("");
			}
		} else {
			if (t.length() == 0) {
				((EditText) v).setText("0");
			}
		}
	}
}
